package com.as.measurement.client.main;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.cm.*;

import com.as.measurement.sender.SenderService;
import com.as.measurements.client.core.models.JperfStreamResult;
import com.as.measurements.client.listener.MeasurementsListener;
import com.as.measurements.client.service.QoSParamsService;

public class MainClient implements MeasurementsListener, MainService {

	/**
	 * Logger
	 */
	private Log _logger = LogFactory.getLog(getClass().getName());

	private QoSParamsService _qosService = null;
	private SenderService _sender = null;

	private boolean inicializated = false;
	private Properties iperfthread;

	public void MainClient() {
		// TODO
	}

	private void init(Properties p) {

		// 1. Get interfaces of the client or take it from a configuration file
		// TODO
		// 2. for each interface get QoS parameters - Client Service

		/*
		 * Every minute, create an inquirer to check the active users
		 */
		final Properties pp = p;
		TimerTask timerTask = new TimerTask() {

			@Override
			public void run() {
				
				
				_logger.info(" //********************************************************//");

				int num = new Integer((String) pp.get("NUM_INTERFACES"))
						.intValue();

				for (int i = 0; i < num; i++) {

					Properties iperfthread = new Properties();
					iperfthread.put("IFACE_NAME", pp
							.get("IFACE_NAME" + (i + 1)));
					iperfthread.put("SERVER_IP", pp.get("SERVER_IP" + (i + 1)));
					iperfthread.put("IFACE_IP", pp.get("IFACE_IP" + (i + 1)));
					iperfthread.put("IPERF_PORT", pp.get("IPERF_PORT"));

					//this.iperfthread = iperfthread;
					_logger.debug(" init measures for interface: "
							+ pp.get("IFACE_NAME" + (i + 1)) + " | server : "
							+ pp.get("SERVER_IP" + (i + 1)));
					_logger.info(" Start measuring >>");
					_logger.info(" parameters .... " + pp.toString());
					_qosService.getQoSParams(iperfthread);
					try {
						Thread.sleep(5000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
				


			}

		};
		Timer timer = new Timer();
		// alert every 4 minutes from now.
		timer.scheduleAtFixedRate(timerTask, 0, 60000);

		// 3. Measurements are sent to the server through notifyMeasurement
		// method

	}

	protected void activate(ComponentContext context) {
		_logger.info("Activated component:" + getClass().getName());
		_qosService = (QoSParamsService) context.locateService("QoS");
		_qosService.addListener(this);

		_sender = (SenderService) context.locateService("SENDER");
		// init();

		// Read properties file.

		String path = System.getProperty("com.as.qos.configuration");

		// TODO Bail out somewhere other than static block?
		Properties properties = new Properties();
		if (path == null) {
			_logger.error("Missing value for required system property 'com.as.qos.configuration'");
			throw new IllegalStateException("Missing value for required system property 'com.as.qos.configuration'");
			
		} else {
			_logger.info("BASE_CONFIG_DIR set to" + path); 
			try {
				//properties.load(new FileInputStream("/home/mcm/myworkspaces/osgiperf2/configuration/services/client.application.properties"));
				
				properties.load(new FileInputStream(path+"/client.application.properties"));
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}


		init(properties);

	}

	protected void deactivate(ComponentContext context) {
		_logger.info("Desactivate component:" + getClass().getName());

	}

	@Override
	public void notifyMeasurement(JperfStreamResult finalResults) {
		// TODO Auto-generated method stub

		try{
		_logger.debug("Sending JperfStreamResult to the server!!  "
				+ finalResults.getID());
		_sender.Send(finalResults);
		}catch (Exception e){
			
			
			_logger.error("" , e);
			finalResults.print();
		}
	}

	// @Override
	// public void updated(Dictionary properties) throws ConfigurationException
	// {
	//		
	// //
	// // try {
	// // Thread.sleep(5000);
	// // } catch (InterruptedException e) {
	// // // TODO Auto-generated catch block
	// // e.printStackTrace();
	// // }
	// // _logger.info("configuration properties file found!!");
	// //
	// // /*
	// // * Activate method will be called in first place. Then, when the
	// // * configuration properties files is read, updated method will be
	// // * called.
	// // */
	// //
	// // // TODO ... If there is any thread taking meaurements, kill it
	// //
	// // // read the configuration file
	// // /*
	// // * NUM_INTERFACES xx
	// // * IFACE_IP1 xxx.xxx.xxx.xxx
	// // * IFACE_NAME1 xx
	// // * SERVER_IP1 xxx.xxx.xxx.xxx
	// // * IFACE_IP2 xxx.xxx.xxx.xxx
	// // * IFACE_NAME2 xxx
	// // * SERVER_IP2 xxx.xxx.xxx.xxx
	// // * [...]
	// // */
	// //
	// // // by the moment when null, return
	// // //TODO check what to do when null properties.
	// //
	// // _logger.debug (" *****\n*********" +
	// // "********\n********************++++" +
	// // "***************\n********+\n" + inicializated);
	// // if (properties == null || inicializated ) return;
	// //
	// // inicializated = true;
	// //
	// // _logger.info (" getting configuration ");
	// //
	// _logger.info(" //********************************************************//");
	// //
	// // Dictionary d = properties;
	// //
	// // Enumeration <String> e = d.keys();
	// //
	// // while (e.hasMoreElements()) {
	// //
	// // String key = e.nextElement();
	// //
	// // _logger.info( " key: " + key + "   value: " + d.get(key));
	// //
	// // }
	// //
	// _logger.info(" //********************************************************//");
	// //
	// // int num = new Integer((String) properties.get("NUM_INTERFACES"))
	// // .intValue();
	// //
	// // for (int i = 0; i < num; i++) {
	// //
	// // Properties iperfthread = new Properties();
	// // iperfthread.put("IFACE_NAME", properties.get("IFACE_NAME"+(i+1)));
	// // iperfthread.put("SERVER_IP", properties.get("SERVER_IP"+(i+1)));
	// // iperfthread.put("IFACE_IP", properties.get("IFACE_IP"+(i+1)));
	// // iperfthread.put("IPERF_PORT", properties.get("IPERF_PORT"));
	// //
	// // _logger.debug(" init measures");
	// // init(iperfthread);
	// // }
	// // _logger.debug (" *****\n*********" +
	// // "********\n********************++++" +
	// // "***************\n********+\n");
	//
	//
	// }

}
